﻿using HZU.ZP.Data.Help;
using HZU.ZP.Data.Interfaces;
using HZU.ZP.Data.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HZU.ZP.Data.Impl
{
    public class MessageDao : IMessageDao
    {
        private EFCoreDbContext _context;

        public MessageDao(EFCoreDbContext context)
        {
            _context = context;
        }
        public void Add(Message message)
        {
            _context.Messages.Add(message);
            _context.SaveChanges();
        }

        public Message GetById(int id)
        {
            return _context.Messages.FirstOrDefault(e => e.Id == id);
        }

        public IList<Message> GetMesList(string fromEmail, string toEmail)
        {
            return _context.Messages.Where(e => (e.FromEmail == fromEmail && e.ToEmail == toEmail) || (e.ToEmail == fromEmail && e.FromEmail == toEmail)).Distinct(new MessageComparer()).ToList();
        }

        public IList<Message> GetMesUserList(string fromEmail, string toId)
        {
            return _context.Messages.Where(e => (e.ToId == toId) || (e.FromEmail == fromEmail)).OrderBy(e => e.ReadState).ThenByDescending(e => e.CreateTime).ToList();
        }

        public void Update(Message message)
        {
            _context.Messages.Update(message);
            _context.SaveChanges();
        }

        public void UpdateList(string sql)
        {
            _context.Database.ExecuteSqlCommand(sql);
        }
    }
}
